<template>
  <div class="search">
    <el-select
      v-model="select"
      placeholder="Select"
      style="width: 100px; margin-right: 10px"
    >
      <el-option
        v-for="item in selectList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-input style="width: 200px; margin-right: 10px" v-model="key"></el-input>
    <el-button type="success" plain @click="search">搜索</el-button>
  </div>
  <div v-if="bookList1.isShow">
    <el-table :data="showList.list" border stripe style="width: 100%">
      <el-table-column prop="name" label="书名" width="180" />
      <el-table-column prop="editor" label="作者" width="180" />
      <el-table-column prop="category" label="类别" />
      <el-table-column prop="press" label="出版社" />
      <el-table-column prop="left" label="剩余数" />
      <el-table-column label="能否借阅">
        <template #default="scope">
          <span style="margin-left: 10px">{{
            scope.row.left > 0 ? "是" : "否"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column>
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :disabled="!(scope.row.left > 0)"
            @click="handleDelete(scope.$index, scope.row)"
            >借阅</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="借阅详情" width="30%">
      <div class="borrow-body">
        <h2>{{ borrowBook.data.name }}</h2>
        <div class="borrow-item">书号：{{ borrowBook.data.ISBN }}</div>
        <div class="borrow-item">类型：{{ borrowBook.data.category }}</div>
        <div class="borrow-item">作者：{{ borrowBook.data.editor }}</div>
        <div class="borrow-item">
          出版社：<el-tag type="info">{{ borrowBook.data.press }}</el-tag>
        </div>
        <div class="borrow-item">剩余数量：{{ borrowBook.data.left }}</div>
        <div class="borrow-item">
          价格：<span class="price">￥{{ borrowBook.data.price }}</span>
        </div>
        <el-input-number
          class="borrow-item"
          v-model="num"
          :min="1"
          :max="borrowBook.data.left"
          size="small"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="borrow"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-pagination
      class="page"
      :total="bookList.length"
      v-model:current-page="page"
      layout="prev, pager, next"
    />
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive, watch } from "vue";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import { pagination } from "../../stores/requestMethod";
const bookList = [
  {
    name: "《黎明之剑》",
    auth: "远瞳",
    category: "科幻",
    isBorrow: false,
  },
  {
    name: "《人间失格》",
    auth: "太宰治",
    category: "现实",
    isBorrow: false,
  },
  {
    name: "《呐喊》",
    auth: "鲁迅",
    category: "小说",
    isBorrow: false,
  },
  {
    name: "《鲁滨逊漂流记》",
    auth: "丹尼尔·笛福",
    category: "小说",
    isBorrow: true,
  },
];
const selectList = [
  {
    value: "name",
    label: "书名",
  },
  {
    value: "category",
    label: "类别",
  },
];
const borrowBook = reactive({
  data: {
    ISBN: "",
    amount: 0,
    attr1: "",
    attr2: "",
    attr3: "",
    attr4: "",
    category: "",
    editor: "",
    left: 0,
    name: "",
    press: "",
    price: 0,
  },
});
const loginAccount = JSON.parse(sessionStorage.getItem("loginAccount"));
const num = ref(1);
const page = ref(1);
let dialogVisible = ref(false);
const bookList1 = reactive({
  list: [],
  isShow: false,
});
const showList = reactive({
  list: [],
});
const select = ref("name");
const key = ref("");
const search = () => {
  if (key.value === "") {
    getAllBooks();
  } else {
    if (select.value === "name") {
      fetch(`http://127.0.0.1:5000/books/name/${key.value}`, {
        method: "GET",
        mode: "cors",
        credentials: "include",
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
          bookList1.list = res.data;
        })
        .catch((err) => console.log(err));
    } else {
      fetch(`http://127.0.0.1:5000/books/category/${key.value}`, {
        method: "GET",
        mode: "cors",
        credentials: "include",
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
          bookList1.list = res.data;
        })
        .catch((err) => console.log(err));
    }
  }
};
const handleDelete = (index, row) => {
  console.log(index, row);
  if (loginAccount === null) {
    ElMessageBox.alert("您还没有登录，请登录", "提示", {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: "OK",
      callback: () => {
        router.push("/login");
      },
    });
  } else {
    borrowBook.data = row;
    dialogVisible.value = true;
  }
};
const borrow = () => {
  fetch(`http://127.0.0.1:5000/lends/${num.value}`, {
    method: "POST",
    credentials: "include",
    mode: "cors",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ReaderID: loginAccount.id,
      ISBN: borrowBook.data.ISBN,
    }),
  })
    .then((res) => res.json())
    .then((res) => {
      console.log(res);
      if(res.msg == '借阅成功！'){
        ElMessage({
          message: "借阅成功",
          type: "success",
        });
      }else{
         ElMessage({
          message: res.msg,
          type: "warning",
        });
      }

      getAllBooks();
      dialogVisible.value = false;
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        message: "出了点问题",
        type: "error",
      });
      dialogVisible.value = false;
    });
};

const getAllBooks = () => {
  fetch("http://127.0.0.1:5000/books", {
    method: "GET",
    mode: "cors",
    credentials: "include",
  })
    .then((response) => response.json())
    .then((data) => {
      bookList1.list = data.data;
      showList.list = pagination(
        10,
        page.value,
        JSON.parse(JSON.stringify(bookList1.list))
      );
      bookList1.isShow = true;
    })
    .catch((err) => console.log(err));
};

onBeforeMount(() => {
  getAllBooks();
});
watch(page, (value, oldValue) => {
  showList.list = pagination(
    10,
    value,
    JSON.parse(JSON.stringify(bookList1.list))
  );
});
</script>

<style scoped>
.search {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 20px;
  text-align: left;
}
.page {
  position: absolute;
  left: 50%;
}
.borrow-body {
  text-align: left;
  margin-left: 10%;
  width: 80%;
}
.borrow-item {
  margin-top: 10px;
}
.price {
  color: #ff5000;
}
</style>
